#include "stdTcp.h"
#include <stdio.h>

#include "StdThread.h"
#include "GlobalMessage.h"
#include "DoubleLinkList.h"

#define ip "172.29.0.125"
#define port 8080

DLlist ClientList;//定义一个全局变量: 在线用户列表

// 需求响应
void SolveRequest(MSG *m, int clientSock)
{
    switch(m->flag)
    {
        case LOGIN:
            InsertDLlistTial(&ClientList, CreateCInfo(m->FromName, clientSock));
            TravelDLlist(&ClientList, PrintCInfo);
            break;
        case CHAT:
            DLlist findList = FindByElement(&ClientList, m->ToName, IsClientNameEqual);
            if (findList.len == 0)
            {
                printf("没有找到名称为[%s]的用户\n", m->ToName);
            }
            else
            {
                CInfo * c = (CInfo *)findList.head->next->data;
                printf("准备给[%s][套接字：%d]的用户发消息\n", c->ClientName, c->sock);
                TcpServerSend(c->sock, m, sizeof(MSG));
            }
            ClearDLlist(&findList, NULL);
            break;

        default:
            break;
    }
}

// 每个客户端线程处理函数
void *ClientThreadHandle(void *arg)
{
    int clientSock = *((int *)arg);
    while (1)
    {
        MSG m;
        char msg[100] = { 0 };
        if (TcpServerRecv(clientSock, &m, sizeof(MSG)) == false)// 0代表阻塞
        {
            //perror("recv error");
            printf("客户端[%d]已下线。。。\n", clientSock);
            return NULL;
        }
        //printf("收到来自客户端[%d]的消息：%s\n", clientSock, msg);
        SolveRequest(&m, clientSock);
    }
}

int main()
{
    InitDLlist(&ClientList);
    TcpS *s = TcpServerInit(ip, port);

    int clientSock = -1;
    // if (clientSock < 0)
    // {
    //     return -1;
    // }

    while ((clientSock = TcpServerAccept(s)) >= 0)// 允许多个客户端相连
    {
        printf("接入新的客户端，套接字是：%d\n", clientSock);
        Thread *t = ThreadInit(ClientThreadHandle, &clientSock);// 开启一个线程让他处理


    }




#if 0
    // 此时进程阻塞在这里，无法执行下面的发送消息
    // 怎么办？
    // 每一个新进来的客户端开辟一个线程,也就是实现大并发服务器

    while (1)
    {
        char msg[100] = { 0 };
        if (TcpServerRecv(clientSock, msg, 100) == false)// 0代表阻塞
        {
            //perror("recv error");
            printf("客户端已下线。。。\n");
            return -1;
        }
        printf("收到来自客户端的消息：%s\n", msg);
    }
#endif

    return 0;
}
